﻿using Owin;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

using ERPStore.Extensions;

using Microsoft.Practices.Unity;

namespace ERPStore.Host.Extensions
{
	public static class OwinExtensions
	{
		public static void ConfigureSignalR(this IAppBuilder appBuilder)
		{
			var signalRSettings = new Microsoft.AspNet.SignalR.ConnectionConfiguration();
			appBuilder.MapSignalR<Logging.LoggerConnection>("/realtime/logger", signalRSettings);

			var container = GlobalConfiguration.Configuration.DependencyResolver.GetContainer();

			var persitentConnectionList = GlobalConfiguration.Configuration.DependencyResolver.GetServices<ERPStore.Services.IPersistentConnection>();

			foreach (var item in persitentConnectionList)
			{
				var realtimeUrl = string.Format("/realtime/{0}", item.Url.TrimStart('/'));
				appBuilder.MapSignalR(realtimeUrl, item.GetType(), signalRSettings);
			}
		}

		public static void ConfigureWebApi(this IAppBuilder appBuilder)
		{
			var container = GlobalConfiguration.Configuration.DependencyResolver.GetContainer();

			var config = new HttpConfiguration();
			var logger = container.Resolve<ERPStore.Logging.ILogger>();

			config.DependencyResolver = new IOC.UnityServiceDependencyResolver(container, config.DependencyResolver);
			// config.MessageHandlers.Add(new Web.Logging.WebApiLoggerHandler());
			config.IncludeErrorDetailPolicy = System.Web.Http.IncludeErrorDetailPolicy.Always;
			config.Filters.Add(new Web.Controllers.ActionFilters.LogExceptionFilter());

			/*
			config.Services.Replace(typeof(System.Web.Http.Tracing.ITraceWriter), new System.Web.Http.Tracing.SystemDiagnosticsTraceWriter()
			{
				IsVerbose = true,
				MinimumLevel = System.Web.Http.Tracing.TraceLevel.Debug
			});*/

			config.Routes.MapHttpRoute(
				name : "CatchAllAPIs",
				routeTemplate: "api/{controller}/{action}/{id}",
				defaults: new { id = RouteParameter.Optional }
			);

			appBuilder.UseWebApi(config);
		}
	}
}
